<?php

namespace App\Http\Controllers\Home;

use App\Model\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use App\Http\Controllers\Controller;

use Gregwar\Captcha\CaptchaBuilder;
use Gregwar\Captcha\PhraseBuilder;
use Session;

class LoginController extends Controller
{
    public function index(){
        return view("home.login");
    }

    //验证码
    public function code(Request $request){
        $phrase = new PhraseBuilder(4, '2345678');

        $builder = new CaptchaBuilder(null, $phrase);

        $builder->build(150,50);

        $phrase = $builder->getPhrase();

        //把内容存入session

        $request->session()->put("code",$phrase); //存储验证码

        ob_clean();

        return response($builder->output())->header('Content-type','image/jpeg');
    }

    //验证
    public function verify(Request $request){
        $input = $request->except('_token');
        $code = session()->get('code');
        //验证规则
        $role = [
            "username"=>"required|between:4,16",
            "password"=>"required",
            "code"=>"required|in:{$code}"
        ];
        //不符合规则返回给前台消息
        $msg = [
            "username.required"=>"用户名不能为空",
            "username.between"=>"用户名必须是4-16位",
            "password.required"=>"密码不能为空",
            "code.in"=>"验证码不正确",

        ];
        //验证
        $validator = Validator::make($input,$role,$msg);
        //验证不成功的时候跳转
        if ($validator->fails()) {
            return redirect('pxkjLogin')
                ->withErrors($validator)
                ->withInput();
        }
        //验证是否有此用户
        $user = User::where("username",$input['username'])->first();
        if(!$user){
            return redirect('pxkjLogin')
                ->withErrors("用户名错误");
        }
        //验证密码
        if(!Hash::check($input['password'],$user->password)){
            return redirect('pxkjLogin')
                ->withErrors("密码错误");
        }

        //保存信息到session
        Session()->put("user",$user);

        //获取用户拥有的栏目权限信息
        Session()->put("cate",$user->cate);

        //跳转到后台首页
        return redirect('home/index/index');


    }

    //无权限访问跳转
    public function noaccess(){
        return view("admin.noaccess");
    }

    public function logout(){
//        清空session
        session()->flush();
        //跳转登陆页面
        return redirect("pxkjLogin");
    }
}
